<template>
  <div class="app-container">
    <!-- 工艺节点标签页 -->
    <el-tabs v-model="activeName" v-if="nodeList.length > 0" style="width: 100%; margin-bottom: 20px;"
             element-loading-text="切换中..."
             @tab-click="handleTabClick">
      <el-tab-pane
        v-for="node in nodeList"
        :key="node.id"
        :label="node.processNodeName"
        :name="node.id.toString()"
        style="width: 100%;"
      >
      </el-tab-pane>
    </el-tabs>

    <!-- 派工对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备" prop="deviceId">
              <el-select v-model="formData.deviceId" placeholder="请输入设备名称进行搜索" filterable style="width: 100%" remote
                         :remote-method="deviceRemoteMethod" :loading="deviceLoading" @change="handleDeviceChange">
                <el-option v-for="device in deviceList" :key="device.id" :label="device.deviceName" :value="device.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="workOrderQuantity">
              <el-input v-model.number="formData.workOrderQuantity" placeholder="请输入数量" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划开始日期" prop="planBeginTime">
              <el-date-picker clearable v-model="formData.planBeginTime" type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择计划开始日期" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束日期" prop="planEndTime">
              <el-date-picker clearable v-model="formData.planEndTime" type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择计划结束日期" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="每日派工数量" prop="daySendWorkNumber">-->
          <!--              <el-input v-model.number="formData.daySendWorkNumber" placeholder="请输入每日派工数量" style="width: 100%"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 搜索工作栏 -->
    <!--    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">-->
    <!--      <el-form-item label="计划编号" prop="planNo">-->
    <!--        <el-input v-model="queryParams.planNo" placeholder="请输入计划编号" clearable @keyup.enter.native="handleQuery"/>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item label="车间" prop="deptId">-->
    <!--        <treeselect v-model="queryParams.deptId" :options="deptList" :normalizer="normalizer" placeholder="选择所属车间" style="width: 200px"/>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item label="产品名称" prop="productName">-->
    <!--        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery"/>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item label="产品编码" prop="productCode">-->
    <!--        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery"/>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item label="工艺路线名称" prop="processRouteName">-->
    <!--        <el-input v-model="queryParams.processRouteName" placeholder="请输入工艺路线名称" clearable-->
    <!--                  @keyup.enter.native="handleQuery"/>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item label="工艺路线类型" prop="routeType">-->
    <!--        <el-select v-model="queryParams.routeType" placeholder="请选择工艺路线类型" clearable size="small">-->
    <!--          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.ROUTE_TYPE)" :key="dict.value" :label="dict.label"-->
    <!--                     :value="parseInt(dict.value)"/>-->
    <!--        </el-select>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item label="状态" prop="status">-->
    <!--        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">-->
    <!--          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.PLAN_STATUS)" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>-->
    <!--        </el-select>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item>-->
    <!--        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>-->
    <!--        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>-->
    <!--      </el-form-item>-->
    <!--    </el-form>-->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
        >派工
        </el-button>
      </el-col>
      <!--          <el-col :span="1.5">-->
      <!--            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"-->
      <!--                       :loading="exportLoading"-->
      <!--                       v-hasPermi="['production:plan:export']">导出-->
      <!--            </el-button>-->
      <!--          </el-col>-->
      <!--          <el-col :span="1.5">-->
      <!--            <el-button-->
      <!--              type="danger"-->
      <!--              plain-->
      <!--              icon="el-icon-delete"-->
      <!--              size="mini"-->
      <!--              :disabled="isEmpty(checkedIds)"-->
      <!--              @click="handleDeleteBatch"-->
      <!--              v-hasPermi="['production:plan:delete']"-->
      <!--            >-->
      <!--              批量删除-->
      <!--            </el-button>-->
      <!--          </el-col>-->
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
              @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="工单号" align="center" prop="workOrderNo" width="200"/>
      <el-table-column label="计划编号" align="center" prop="planNo" width="200"/>
      <el-table-column label="车间名称" align="center" prop="deptName" width="150"/>
      <el-table-column label="产品名称" align="center" prop="productName" width="200"/>
      <el-table-column label="产品编码" align="center" prop="productCode" width="150"/>
      <el-table-column label="工艺路线名称" align="center" prop="processRouteName" width="150"/>
      <el-table-column label="工艺路线类型" align="center" prop="routeTypeName" width="150"/>
      <el-table-column label="计划开始时间" align="center" prop="planBeginTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.planBeginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="planEndTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.planEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际开始时间" align="center" prop="actualBeginTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.actualBeginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际结束时间" align="center" prop="actualEndTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.actualEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划数量" align="center" prop="planQuantity" width="150"/>
      <el-table-column label="已完成数量" align="center" prop="completeQuantity" width="150"/>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.PLAN_STATUS, scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">-->
      <!--        <template v-slot="scope">-->
      <!--          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"-->
      <!--                     v-hasPermi="['production:plan:update']">修改-->
      <!--          </el-button>-->
      <!--          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"-->
      <!--                     v-hasPermi="['production:plan:update']">派工-->
      <!--          </el-button>-->
      <!--          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
      <!--                     v-hasPermi="['production:plan:delete']">删除-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
  </div>
</template>

<script>
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as PlanApi from '@/api/production/plan';
import * as WorkOrderApi from '@/api/production/workorder';
import * as ProcessRouteProcessNodeApi from "@/api/basic/processrouteprocessnode";
import * as DeviceApi from '@/api/system/device';

export default {
  name: "DispathWork",
  components: {
    Treeselect
  },
  data() {
    return {
      planId: null,
      deptList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产计划列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      nodeList: [],
      // 激活的标签页ID
      activeName: '',
      // 工作订单列表
      workOrderList: [],
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '派工',
      formLoading: false,
      // 表单数据
      formData: {
        id: undefined,
        planId: null,
        processRouteNodeId: undefined,
        deviceId: undefined,
        deviceName: undefined,
        workOrderQuantity: undefined,
        planBeginTime: undefined,
        planEndTime: undefined,
        daySendWorkNumber: undefined
      },
      // 设备列表
      deviceList: [],
      // 设备加载状态
      deviceLoading: false,
      // 表单验证规则
      formRules: {
        deviceId: [{required: true, message: '设备不能为空', trigger: 'blur'}],
        workOrderQuantity: [{required: true, message: '数量不能为空', trigger: 'blur'}]
      },
      pageInfo: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        planNo: null,
        deptId: null,
        deptName: null,
        productId: null,
        productName: null,
        productCode: null,
        processRouteId: null,
        processRouteName: null,
        routeType: null,
        routeTypeName: null,
        planBeginTime: [],
        planEndTime: [],
        actualBeginTime: [],
        actualEndTime: [],
        status: null,
        createTime: [],
      },
    };
  },
  created() {
    // 初始化时获取路由参数
    if (this.$route.query.planId) {
      this.planId = this.$route.query.planId;
      this.getPlanInfo(this.planId);
    }
  },
  watch: {
    // 监听路由参数变化，解决页面缓存问题
    '$route.query.planId': {
      handler(newPlanId, oldPlanId) {
        if (newPlanId && newPlanId !== oldPlanId) {
          this.planId = newPlanId;
          this.getPlanInfo(newPlanId);
        }
      },
      immediate: false
    }
  },
  methods: {
    // 处理标签页切换
    handleTabClick(tab) {
      // 使用当前选中标签页的工艺节点ID更新查询参数
      this.queryParams.processRouteNodeId = parseInt(tab.paneName);
      // 重新加载列表数据
      this.getList();
    },

    async getPlanInfo(id) {
      try {
        // 等待getPlan执行完毕
        const res = await PlanApi.getPlan(id);
        this.pageInfo = res.data;

        // 确保processRouteId存在后再调用getNodeAll
        if (this.pageInfo && this.pageInfo.processRouteId) {
          const resq = await ProcessRouteProcessNodeApi.getNodeAll({
            processRouteId: this.pageInfo.processRouteId,
            id: this.pageInfo.processRouteId
          });
          this.nodeList = resq.data || [];
          if (this.nodeList.length > 0) {
            // 设置计划ID
            this.queryParams.planId = id;
            // 使用第一个工艺节点ID作为查询参数
            this.queryParams.processRouteNodeId = this.nodeList[0].id;
            // 设置激活的标签页ID
            this.activeName = this.nodeList[0].id.toString();
            // 重新加载列表数据
            this.getList();
          }

        } else {
          this.nodeList = [];
          console.warn('未找到有效的工艺路线ID');
          this.$modal.msgError("未找到有效的工艺路线");
          this.loading = false;
        }
      } catch (error) {
        console.error('获取计划信息失败:', error);
        this.nodeList = [];
      }
    },
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      // 关键：如果不是第三级节点，则禁用
      return {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };
    },
    getOptions() {
      listDept().then(response => {
        this.deptList = this.handleTree(response.data, "id")[0].children;
      });
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await WorkOrderApi.getWorkOrderPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    // 打开派工对话框
    async openForm(id) {
      this.dialogVisible = true;
      this.deviceRemoteMethod('')
      this.resetForm();
      // 初始化表单数据，设置当前选中的工艺节点ID和计划ID
      this.formData.processRouteNodeId = this.queryParams.processRouteNodeId;
      this.formData.planId = this.queryParams.planId;

      // 将pageInfo中的计划开始时间和结束时间带入表单，如果存在的话
      if (this.pageInfo) {
        if (this.pageInfo.planBeginTime) {
          this.formData.planBeginTime = this.pageInfo.planBeginTime;
        }
        if (this.pageInfo.planEndTime) {
          this.formData.planEndTime = this.pageInfo.planEndTime;
        }
      }
      // 加载设备列表
    },

    // 设备远程搜索方法
    async deviceRemoteMethod(query) {
      this.deviceLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          deviceName: query,
        };
        const response = await DeviceApi.getDevicePage(params);
        this.deviceList = response.data.list;
      } catch (error) {
        console.error('搜索设备失败', error);
        this.deviceList = [];
      } finally {
        this.deviceLoading = false;
      }
    },

    // 处理设备选择
    handleDeviceChange(deviceId) {
      const selectedDevice = this.deviceList.find(device => device.id === deviceId);
      if (selectedDevice) {
        this.formData.deviceName = selectedDevice.deviceName;
      } else {
        this.formData.deviceName = undefined;
      }
    },

    // 重置表单
    resetForm() {
      this.formData = {
        id: undefined,
        planId: this.queryParams.planId,
        processRouteNodeId: this.queryParams.processRouteNodeId,
        deviceId: undefined,
        deviceName: undefined,
        workOrderQuantity: undefined,
        planBeginTime: undefined,
        planEndTime: undefined,
        daySendWorkNumber: 0
      };
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },

    // 提交表单
    async submitForm() {
      // 校验表单
      await this.$refs.formRef.validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 调用更新工作订单方法
        await WorkOrderApi.createWorkOrder(data);
        this.$modal.msgSuccess("派工成功");
        this.dialogVisible = false;
        // 重新加载列表
        this.getList();
      } catch (error) {
        console.error('派工失败', error);
        this.$modal.msgError("派工失败，请重试");
      } finally {
        this.formLoading = false;
      }
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除生产计划编号为"' + id + '"的数据项?')
      try {
        await PlanApi.deletePlan(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除生产计划 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await PlanApi.deletePlanList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有生产计划数据项?');
      try {
        this.exportLoading = true;
        const data = await PlanApi.exportPlanExcel(this.queryParams);
        this.$download.excel(data, '生产计划.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
  }
};
</script>
